﻿using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Zj.CourseManage.Domain.Core;
using Zj.CourseManage.Domain.Events;
using Zj.CourseManage.Domain.Students;

namespace Zj.CourseManage.EventHandler
{
    public class StudentCreatedEventHandler : IEventHandler<StudentCreatedEvent>
    {
        private readonly IEventStore _eventStore;
        public StudentCreatedEventHandler(IEventStore eventStore)
        {
            this._eventStore = eventStore;
        }

        public bool CanHandle(IEvent @event, CancellationToken cancellationToken = default(CancellationToken))
            => @event.GetType() == typeof(StudentCreatedEvent);

        public Task<bool> CanHandle(StudentCreatedEvent @event)
            => Task.FromResult(true);

        public bool CanHandle(IEvent @event)
        {
            throw new NotImplementedException();
        }

        public Task<bool> HandleAsync(IEvent @event,CancellationToken cancellationToken=default(CancellationToken))
        {
            //var descriptor = new EventDescriptor() {  EventPayload=this._messageSerializer.Serialize(@event)   };
            this._eventStore.SaveAsync(new List<IEvent>() { @event }, cancellationToken);
            return CanHandle(@event) ? HandleAsync(@event) : Task.FromResult(false);
        }

        public Task<bool> HandleAsync(StudentCreatedEvent @event, CancellationToken cancellationToken = default(CancellationToken))
        {
            return HandleAsync(@event, cancellationToken);
        }
    }
}
